import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Box,
  Paper,
  Typography,
  TextField,
  Button,
  CircularProgress,
  Snackbar,
  Alert,
  Grid,
  Divider,
  Card,
  CardContent,
  IconButton,
  InputAdornment,
  Tooltip,
} from '@mui/material';
import {
  ArrowBack as ArrowBackIcon,
  Save as SaveIcon,
  Cancel as CancelIcon,
  Visibility as VisibilityIcon,
  VisibilityOff as VisibilityOffIcon,
} from '@mui/icons-material';
import apiClient from '../services/apiService';
import { Device as DeviceType } from '../types/device';

interface Device {
  deviceId: string;
  name: string;
  type: string;
  status: 'online' | 'offline';
  lastHeartbeat: string;
}

const DeviceEdit: React.FC = () => {
  const { deviceId } = useParams<{ deviceId: string }>();
  const navigate = useNavigate();
  const [device, setDevice] = useState<Device | null>(null);
  const [name, setName] = useState('');
  const [type, setType] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

  useEffect(() => {
    let mounted = true;

    const fetchDevice = async () => {
      if (!deviceId) {
        setError('设备ID不能为空');
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const response = await apiClient.get(`/devices/${deviceId}`);
        if (mounted) {
          setDevice(response.data);
          setName(response.data.name);
          setType(response.data.type);
          setError(null);
        }
      } catch (error: any) {
        if (mounted) {
          setError(error.response?.data?.message || '获取设备信息失败');
          if (error.response?.status === 404) {
            navigate('/devices');
          }
        }
      } finally {
        if (mounted) {
          setLoading(false);
        }
      }
    };

    fetchDevice();

    return () => {
      mounted = false;
    };
  }, [deviceId, navigate]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!deviceId) return;

    try {
      setIsSubmitting(true);
      const response = await apiClient.put(`/devices/${deviceId}`, {
        name,
        type,
        password: password || undefined
      });
      navigate(`/devices/${deviceId}`);
    } catch (error: any) {
      setError(error.response?.data?.message || '更新设备失败');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  if (!deviceId) {
    return (
      <Box sx={{ mt: 4 }}>
        <Typography color="error">设备ID不能为空</Typography>
        <Button onClick={() => navigate('/devices')} sx={{ mt: 2 }}>
          返回设备列表
        </Button>
      </Box>
    );
  }

  if (!device) {
    return (
      <Box sx={{ mt: 4 }}>
        <Typography color="error">设备不存在</Typography>
        <Button onClick={() => navigate('/devices')} sx={{ mt: 2 }}>
          返回设备列表
        </Button>
      </Box>
    );
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
        <Tooltip title="返回设备列表">
          <IconButton onClick={() => navigate('/devices')} sx={{ mr: 2 }}>
            <ArrowBackIcon />
          </IconButton>
        </Tooltip>
        <Typography variant="h4">
          编辑设备
        </Typography>
      </Box>

      <Card sx={{ maxWidth: 800, mx: 'auto' }}>
        <CardContent>
          <form onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="设备ID"
                  value={device.deviceId}
                  disabled
                  variant="outlined"
                  InputProps={{
                    sx: { bgcolor: 'action.disabledBackground' }
                  }}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="设备名称"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  required
                  variant="outlined"
                  placeholder="请输入设备名称"
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="设备类型"
                  value={type}
                  onChange={(e) => setType(e.target.value)}
                  required
                  variant="outlined"
                  placeholder="请输入设备类型"
                />
              </Grid>
              <Grid item xs={12}>
                <Divider sx={{ my: 2 }}>
                  <Typography variant="subtitle1" color="text.secondary">
                    修改密码
                  </Typography>
                </Divider>
                <TextField
                  fullWidth
                  label="新密码"
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  variant="outlined"
                  placeholder="如果不修改密码，请留空"
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          onClick={() => setShowPassword(!showPassword)}
                          edge="end"
                        >
                          {showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                />
              </Grid>
              <Grid item xs={12}>
                <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2, mt: 2 }}>
                  <Button
                    variant="outlined"
                    onClick={() => navigate('/devices')}
                    disabled={isSubmitting}
                    startIcon={<CancelIcon />}
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    color="primary"
                    disabled={isSubmitting}
                    startIcon={isSubmitting ? <CircularProgress size={20} /> : <SaveIcon />}
                  >
                    {isSubmitting ? '保存中...' : '保存'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>

      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={() => setError(null)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert 
          onClose={() => setError(null)} 
          severity="error"
          variant="filled"
          sx={{ width: '100%' }}
        >
          {error}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default DeviceEdit; 